package com.spark.incoicings.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.incoicings.dao.OrderMapper;
import com.spark.incoicings.dao.PurchaseDetailsMapper;
import com.spark.incoicings.service.OrderService;
import com.spark.incoicings.utils.RandomGenerateUtil;
import com.spark.invoicings.entity.Code;
import com.spark.invoicings.entity.Order;
import com.spark.invoicings.entity.PurchaseDetail;
import com.spark.invoicings.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private PurchaseDetailsMapper purchaseDetailMapper;

    @Resource
    private RandomGenerateUtil randomGenerateUtil;

    @Override
    public List<Order> selectOrderStatusAll() {
        return orderMapper.selectOrderStatusAll();
    }

    @Override
    public Order selectOrderById(Integer id) {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询所有采购订单
     * 分页
     *
     * @param map
     * @return
     */
    @Override
    public List<Order> selectOrderAll(Map<String, Object> map) {
        return orderMapper.selectOrderAll(map);
    }

    /**
     * 添加采购订单及采购明细
     *
     * @param order
     * @return
     */
    @Transactional
    @Override
    public Result addOrder(Order order) {
        Order data = setOrder(order);
        data.setPurchaseOrderNumber(code("CG"));
        // 执行采购订单添加
        if (orderMapper.insert(data) > 0) {
            // 给所属订单id赋值并执行采购订单明细添加
            order.getPurchaseDetails().forEach(purchaseDetail -> {
                purchaseDetail.setPurchaseOrderId(data.getPurchaseOrderId());
                purchaseDetail.setPendingArrivalQuantity(purchaseDetail.getPurchaseQuantity());
                purchaseDetailMapper.insert(purchaseDetail);
            });
            return Result.success(200, "success", order.getPurchaseOrderId());
        }
        return Result.error(500, "保存失败");
    }

    /**
     * 采购订单及采购订单明细根据id更新
     * @param order
     * @return
     */
    @Override
    public boolean updateOrderById(Order order) {
        Order data = setOrder(order);
        data.setModifyTime(new Date());
        if (orderMapper.updateById(data) > 0) {
            order.getPurchaseDetails().forEach(purchaseDetail -> purchaseDetailMapper.updateById(purchaseDetail));
            return true;
        }
        return false;
    }


    // 金额计算及默认值赋值
    private Order setOrder(Order order) {
        // --
        // 采购总数
        int quantity = 0;
        // 所有采购总额
        double priceTotal = 0;
        // 计算采购订单明细金额
        for (PurchaseDetail purchaseDetail : order.getPurchaseDetails()) {
            quantity += purchaseDetail.getPurchaseQuantity();
            priceTotal += purchaseDetail.getPurchasePrice() * purchaseDetail.getPurchaseQuantity();
            // 采购明细总额
            purchaseDetail.setTotalPurchaseAmount(purchaseDetail.getPurchasePrice() * purchaseDetail.getPurchaseQuantity());
            // 应付金额
            purchaseDetail.setPayableAmount(purchaseDetail.getPurchasePrice() * purchaseDetail.getPurchaseQuantity());
        }
        // --

        // -- 计算采购订单金额

        // 延期状态默认为 118=>[正常]
        order.setAbnormalStateId(118);
        // 创建人
        order.setCreator(order.getPurchaseApplicant());
        // 修改人
        order.setModifier(order.getPurchaseApplicant());
        // 创建时间
        order.setCreateTime(new Date());
        // 修改时间
        order.setModifyTime(new Date());
        // 最后活动时间
        order.setLastActivityTime(new Date());
        // 采购总数
        order.setTotalQuantity(quantity);
        // 未入库数量
        order.setUnstockedQuantity(quantity);
        // 采购总额
        order.setTotalAmount(priceTotal);
        // 待付款金额
        order.setPendingPaymentAmount(priceTotal);
        // 已付款金额
        order.setPaidAmount(0);
        // 待回票金额
        order.setPendingReceiptAmount(priceTotal);
        // 已回票金额
        order.setReceivedAmount(0);
        // --
        return order;
    }


    // 采购单号生成
    private String code(String type) {
        Code code = new Code();
        code.setType(type);
        code.setText(code.getType() + "%s%s");
        String cgId = randomGenerateUtil.nextSerialNumber(code);
        return cgId;
    }

}
